package com.skivingcloud.admin.sys.controller;

import com.skivingcloud.admin.annotation.UserOperateLog;
import com.skivingcloud.admin.contants.UrlConstant;
import com.skivingcloud.admin.sys.entity.User;
import com.skivingcloud.admin.sys.entity.AppRouteRecordRaw;
import com.skivingcloud.admin.sys.entity.MenuBean;
import com.skivingcloud.admin.sys.entity.SysOrg;
import com.skivingcloud.admin.sys.service.ISysMenuService;
import com.skivingcloud.admin.sys.service.ISysOrgService;
import com.skivingcloud.admin.sys.service.IUserService;
import com.skivingcloud.admin.utils.UserUtil;
import com.skivingcloud.common.contants.Constant;
import com.skivingcloud.common.exception.BusinessException;
import com.skivingcloud.common.utils.PageUtils;
import com.skivingcloud.common.utils.R;
import com.skivingcloud.common.utils.TreeUtils;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * 权限相关
 * @author hushouquan
 *
 */
@RestController
@RequestMapping(UrlConstant.WEB_ADMIN_URL+"/userAuth")
public class SysUserAuthController {

	private static Logger log = LoggerFactory.getLogger(SysUserAuthController.class);
	
	@Autowired
	private ISysMenuService sysMenuService;
	@Autowired
	private IUserService userService;
	@Autowired
	private ISysOrgService sysOrgService;
	
	/**
	 * 导航菜单，根据终端组织的菜单
	 * @param terminal 必须传入，可参考 {@link com.skivingcloud.common.contants.Constant.TerminalType}
	 * @return
	 */
	@GetMapping("/navByTerminal/{terminal}")
	public R navByTerminal(@PathVariable("terminal") String terminal, HttpServletRequest request) {
		User user = (User) UserUtil.getUser();
		String sessionId = request.getRequestedSessionId();
		try {
			//			String[]  terminals = getTerminals(terminal, request);
			List<MenuBean> menuList = sysMenuService.getUserMenuList(user.getId(), terminal, sessionId);
			// 查询按钮权限列表
			Set<String> permissions = sysMenuService.getUserPermissions(user.getId(), terminal);
			return R.ok().put("menuList", menuList).put("permissions", permissions);
		} catch (BusinessException e) {
			return R.error(e.getMessage());
		} catch (Exception e) {
			log.error("根据终端组织的菜单失败", e);
			return R.error("根据终端组织的菜单失败");
		}

	}
	
	/**
	 * 导航菜单，根据终端组织的菜单
	 * 
	 * @param terminal 必须传入，可参考
	 *                 {@link com.skivingcloud.common.contants.Constant.TerminalType}
	 * @return
	 */
	@GetMapping("/navByTerminalRoute/{terminal}")
	public R navByTerminalRoute(@PathVariable("terminal") String terminal, HttpServletRequest request) {
		User user = (User) UserUtil.getUser();
		String sessionId = request.getRequestedSessionId();
		try {
			// String[] terminals = getTerminals(terminal, request);
			List<MenuBean> menuList = sysMenuService.getUserMenuList(user.getId(), terminal, sessionId);
			// List<AppRouteRecordRaw> routes = sysMenuService.getUserMenuListRoute(user.getId(), terminal, sessionId);
			List<Map<String, Object>> data = sysMenuService.getUserMenuListData(user.getId(), terminal);
			// 查询按钮权限列表
			Set<String> permissions = sysMenuService.getUserPermissions(user.getId(), terminal);
			return R.ok().put("type", "adminMenu").put("menuList", menuList).put("data", data).put("permissions", permissions);
		} catch (BusinessException e) {
			return R.error(e.getMessage());
		} catch (Exception e) {
			log.error("根据终端组织的菜单失败", e);
			return R.error("根据终端组织的菜单失败");
		}

	}
	
	/**
     * 获取登录的用户信息
     */
    @GetMapping("/info")
    public R info() {
        Session session = SecurityUtils.getSubject().getSession();
        User user = (User) session.getAttribute(Constant.USERSESSION);
		SysOrg org = sysOrgService.getById(user.getOrgId());
		if(org != null){
			user.setOrgName(org.getOrgName());
		}
        return R.ok().put("user", user);
    }
    
    
    /**
     * 导航菜单,常用菜单选择树
     * @param terminal
     * @return
     */
	@GetMapping("/getCommUseMenuSetTree/{terminal}")
	public R getCommUseMenuSetTree() {
		User user = UserUtil.getUser();
		try {
			List<Map<String, Object>> menuList = sysMenuService.getCommUseMenuSetTree(user.getId(), Constant.TerminalType.TERMINALTYPE_PC.getValue());
			List<TreeUtils> listTree = TreeUtils.getTreeListMap(menuList, "id", "parent_id", "name", "disabled", null);
			List<MenuBean> menucheckList = sysMenuService.getMenuCheckList(user.getId(), Constant.TerminalType.TERMINALTYPE_PC.getValue());
			return R.ok().put("menuList", listTree).put("menucheckList", menucheckList);
		} catch (Exception e) {
			return R.error(998, "查询数据失败");
		}
	}
	
	/**
	 * 设置常用菜单
	 * @param obj
	 * @return
	 */
	@UserOperateLog(module="系统功能",methods="saveCommUseMenu",description="设置常用菜单")
	@PostMapping("/saveCommUseMenu")
	public R saveCommUseMenu(@RequestBody JSONObject obj) {
		try {
			User user = UserUtil.getUser();
			JSONArray array = JSONArray.fromObject(obj.get("ids")) ;
			String[] ids = new String[array.size()];
			for(int i = 0; i < array.size(); i++) {
				ids[i] = array.getString(i);
			}
			sysMenuService.saveCommUseMenu(ids, user);
			return R.ok();
		} catch (Exception e) {
			log.error("保存常用功能失败", e);
			return R.error(998,"保存失败" + e.getMessage());
		}
	}
	
	/**
	 * 导航菜单,常用菜单
	 */
	@GetMapping("/getCommUseMenuTreeByTerminal/{terminal}")
	public R getCommUseMenuTreeByTerminal(@PathVariable("terminal") String terminal, HttpServletRequest request) {
		User user = UserUtil.getUser();
		try {
			String[] terminals = { terminal };
			List<MenuBean> menuList = sysMenuService.getCommUseMenuTreeByTerminal(user.getId(), terminals);
			return R.ok().put("commUseMenu", menuList);
		} catch (BusinessException e) {
			return R.error(e.getMessage());
		} catch (Exception e) {
			log.error("根据终端组织的菜单失败", e);
			return R.error("根据终端组织的菜单失败");
		}
	}
	
	/**
	 * 比较通用的用户查询，只查当前租户的，查询条件为部门名称和姓名
	 * 
	 * @param params
	 * @return
	 */
	@GetMapping("/queryUserSkiving")
	public R queryUserSkiving(@RequestParam Map<String, Object> params) {
		User user = UserUtil.getUser();
		PageUtils page = userService.queryUserSkiving(params, user);
		return R.ok().put("page", page);
	}
}
